package xyz.liut.volley;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.util.LruCache;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import xyz.liut.liutlibrarys.R;


/**
 * Created by liut_ on 2016/5/30.
 */

public class LiutVolley {

    private static LiutVolley volley;
    private RequestQueue queue;
    private LruCache<String, Bitmap> lruCache = new LruCache<>(20);

    //单子模式
    public static synchronized LiutVolley getInstance(Context context) {
        if (volley == null) {
            return new LiutVolley(context);
        } else {
            return volley;
        }
    }

    //私有构造器
    private LiutVolley(Context context) {
        queue = Volley.newRequestQueue(context);
    }

    //返回queue
    public RequestQueue getRequestQueue() {
        return queue;
    }

    //返回lruCache
    public LruCache<String, Bitmap> getCache() {
        return lruCache;
    }


    //GET方式 获取字符串结果
    public void getStringRequest(@NonNull String url, final VolleyListener lsitener) {
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (lsitener != null) {
                    lsitener.onSuccess(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (lsitener != null) {
                    lsitener.onFailure(error);
                }
            }
        }) {
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String parsed;
                try {
                    parsed = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    parsed = new String(response.data);
                }
                return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        queue.add(request);
    }

    //POST方式 获取字符串结果
    public void postStringRequest(@NonNull String url, final Map<String, String> params, final VolleyListener lsitener) {
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (lsitener != null) {
                    lsitener.onSuccess(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (lsitener != null) {
                    lsitener.onFailure(error);
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                if (params != null) {
                    return params;
                } else {
                    return super.getParams();
                }
            }
        };
        queue.add(request);
    }

    //获取图片并缓存
    public void getBitmapWithCache(final String url, final ImageView imageView) {
        getBitmapWithCache(url, imageView, R.drawable.no_img, 0, 0);
    }

    //获取图片并缓存并指定大小
    public void getBitmapWithCache(final String url, final ImageView imageView, int maxWidth, int maxHeight) {
        getBitmapWithCache(url, imageView, R.drawable.no_img, maxWidth, maxHeight);
    }

    //获取图片并缓存、指定大小 有默认图
    public void getBitmapWithCache(final String url, final ImageView imageView, int resId, int maxWidth, int maxHeight) {
        imageView.setTag(url);
        if (resId == 0) {
            resId = R.drawable.no_img;
        }
        final int finalResId = resId;
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public void putBitmap(String key, Bitmap value) {
                lruCache.put(key, value);
            }

            @Override
            public Bitmap getBitmap(String key) {
                return lruCache.get(key);
            }
        };
        ImageLoader mImageLoader = new ImageLoader(queue, imageCache);

        ImageLoader.ImageListener listener = new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() != null) {
                    if (imageView.getTag().equals(url)) {
                        imageView.setImageBitmap(response.getBitmap());
                    }
                } else {
                    imageView.setImageResource(finalResId);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                imageView.setImageResource(finalResId);
            }
        };
        mImageLoader.get(url, listener, maxWidth, maxHeight);
    }

    //获取bitmap
    public void getBitmapRequest(String url, ImageView imageView) {
        getBitmapRequest(url, 0, 0, imageView);
    }

    //获取bitmap并定义高宽
    public void getBitmapRequest(String url, int width, int height, final ImageView imageView) {
        ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                imageView.setImageBitmap(response);
            }
        }, width, height,
                ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, null);
        queue.add(request);
    }

    //获取bitmap并定义高宽
    public void getBitmapRequest(String url, int width, int height, Response.Listener<Bitmap> listener) {
        ImageRequest request = new ImageRequest(url, listener, width, height,
                ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, null);
        queue.add(request);
    }

}
